package com.atguigu.marketing.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.marketing.bean.MarketingRule;
import com.atguigu.marketing.bean.MarketingRuleGroup;
import com.atguigu.marketing.bean.MarketingRuleTime;
import com.atguigu.marketing.service.MarketingRuleService;
import com.atguigu.userprofile.bean.UserGroup;
import com.atguigu.userprofile.service.UserGroupService;
import com.atguigu.userprofile.utils.RedisUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 营销规则 前端控制器
 * </p>
 *
 * @author zhangchen
 * @since 2023-02-02
 */
@RestController
@RequestMapping("/marketing-rule")
public class MarketingRuleController {
    //1    营销规则列表
    //2    按id 查看营销规则
    //3    分群列表 （多选）
    //4    预估人数
    //5   渠道模板  选择列表
    //6    添加渠道模板
    //7   渠道模板列表
    //8   渠道模板保存
    //9  渠道模板根据id查询
    //10  保存营销规则


    @Autowired
    MarketingRuleService marketingRuleService;

    @Autowired
    UserGroupService userGroupService;

    /**
     * 1    营销规则列表
     * @return
     */
    @GetMapping("/list")
    @CrossOrigin
    public List<MarketingRule> getMarketingRuleList(){
        List<MarketingRule> marketingRuleList = marketingRuleService.getMarketingRuleList();
        Map<Long,UserGroup> userGroupAllMap = getUserGroupMap();

        for (MarketingRule marketingRule : marketingRuleList) {
            marketingRule.setPushTimeInfo(genPushTimeInfo(marketingRule.getMarketingRuleTime()));
            marketingRule.setDateInfo(genDateInfo(marketingRule.getMarketingRuleTime()));
            marketingRule.setGroupInfo(genGroupInfo(marketingRule.getMarketingRuleGroup(),userGroupAllMap));
            marketingRule.setChannelTypeName(genChannelTypeName(marketingRule.getMarketingRuleChannel().getChannelType()));
        }
        return marketingRuleList;
    }

    //3    分群列表 （多选）
    @GetMapping("/user-group-options")
    @CrossOrigin
    public List<UserGroup> getUserGroupOption(){
        return   userGroupService.list();
    }


    @PostMapping("/detail")
    @CrossOrigin
    public String saveMarketingRule(@RequestBody  MarketingRule marketingRule){
        marketingRuleService.saveMarketingRule(marketingRule);

        return "success";
    }
    @CrossOrigin
    @GetMapping("/detail/{id}")
    public MarketingRule getMarketingRule(@PathVariable("id") String id){
        MarketingRule marketingRule = marketingRuleService.getMarketingRule(id);
        return marketingRule;
    }

    private  String genPushTimeInfo(MarketingRuleTime marketingRuleTime){
        StringBuilder info=new StringBuilder();

        if(marketingRuleTime!=null&&marketingRuleTime.getPushType()!=null&&marketingRuleTime.getPushType().equals("1")){
            if(marketingRuleTime.getOnceTime()!=null){
                info.append("于").append(DateFormatUtils.format(marketingRuleTime.getOnceTime(),"yyyy年MM月dd日 HH:mm") );
            }
        } else if(marketingRuleTime!=null&&marketingRuleTime.getPushType()!=null&&marketingRuleTime.getPushType().equals("2")){
            if(marketingRuleTime.getLoopType()!=null&&marketingRuleTime.getLoopType().equals("1")){
                info.append("每天 ");
                info.append(marketingRuleTime.getLoopTime());
            }  else if(marketingRuleTime.getLoopType()!=null&&marketingRuleTime.getLoopType().equals("2")){
                info.append("每周 ");
                info.append( getWeekDay(  marketingRuleTime.getLoopWeekDay()));
                info.append(marketingRuleTime.getLoopTime());
            }else if(marketingRuleTime.getLoopType()!=null&&marketingRuleTime.getLoopType().equals("3")){
                info.append("每月 ");
                info.append(marketingRuleTime.getLoopMonthDay()+"日");
                info.append(marketingRuleTime.getLoopTime());
            }
        }else if(marketingRuleTime!=null&&marketingRuleTime.getPushType()!=null&&marketingRuleTime.getPushType().equals("3")){
            info.append("当"+genEvent(marketingRuleTime.getTriggerEvent())+"时");

        }

        return  info.toString();

    }


    private String genDateInfo(MarketingRuleTime marketingRuleTime){
        StringBuilder dateInfoSB=new StringBuilder();
        if(marketingRuleTime!=null&&marketingRuleTime.getFromDt()!=null){
            dateInfoSB.append( "从" +  DateFormatUtils.format(marketingRuleTime.getFromDt(),"yyyy年MM月dd日"));
        }
        if (marketingRuleTime!=null&&marketingRuleTime.getToDt()!=null){
          // dateInfoSB.append( "至" + DateFormatUtil.toDate(marketingRuleTime.getToDt().getTime()));
            dateInfoSB.append( "至" +  DateFormatUtils.format(marketingRuleTime.getToDt(),"yyyy年MM月dd日"));
        }
        return   dateInfoSB.toString() ;
    }

    private String getWeekDay(Integer weekDayNum){
        switch (weekDayNum){
            case 1 : return  "周一";
            case 2 : return  "周二";
            case 3 : return  "周三";
            case 4 : return  "周四";
            case 5 : return  "周五";
            case 6 : return  "周六";
            case 7 : return  "周日";
        }
        return "";
    }

    private String genEvent(String event){
        if  (event.equals("HOME")){
            return  "进入首页" ;
        }else if(event.equals("DETAIL")){
            return  "进入商品详情页" ;
        }else if(event.equals("FAVOR")){
            return  "收藏" ;
        }else if(event.equals("CART")){
            return  "加入购物车" ;
        }else if(event.equals("ORDER")){
            return  "下单" ;
        }else if(event.equals("PAY")){
            return  "支付成功" ;
        }
        return "";
    }

    private  String genGroupInfo(MarketingRuleGroup marketingRuleGroup , Map<Long,UserGroup> userGroupAllMap){
        if(marketingRuleGroup==null){
            return "";
        }
        StringBuilder groupInfoSB=new StringBuilder();
        List<String> groupIdList = marketingRuleGroup.getGroupIds();

        if(groupIdList!=null&&groupIdList.size()>0){
            for (String groupId : groupIdList) {
                UserGroup userGroup = userGroupAllMap.get(Long.parseLong(groupId));
                if(groupInfoSB.length()>0){
                    groupInfoSB.append(";");
                }
                groupInfoSB.append(userGroup.getUserGroupName());
            }
        }

        return groupInfoSB.toString();


    }


    private Map getUserGroupMap(){
        List<UserGroup> userGroupList = userGroupService.list();
        Map<Long,UserGroup>  userGroupMap=new HashMap();
        for (UserGroup userGroup : userGroupList) {
            userGroupMap.put(userGroup.getId(),userGroup);
        }
        return userGroupMap;
    }

    @PostMapping("/evaluteUserGroup")
    @CrossOrigin
    private Integer evaluateUserGroup( @RequestBody List<String> groupIdsList ){
        Jedis jedis = RedisUtil.getJedis();
        String[] groupIdsArr= groupIdsList.stream().map(groupId -> "user_group:" + groupId).toArray(String[]::new);
        Set<String> userIdSet = jedis.sunion(groupIdsArr);
        jedis.close();
        return  userIdSet.size();
    }



    private String genChannelTypeName(String channelType){
        if(channelType!=null){
            if  (channelType.equals("SMS")){
                return  "短信" ;
            }else if(channelType.equals("API")){
                return  "API接口" ;
            }else if(channelType.equals("APP")){
                return  "APP通知" ;
            }else if(channelType.equals("EMAIL")){
                return  "邮件" ;
            }else if(channelType.equals("SITE")){
                return  "站内信" ;
            }
        }
        return "";
    }

}

